// pages/order-pages/order-list/index.js
import { ORDERLIST_TABS, ORDER_TYPE_ENUM } from '../../../constants/order';
import { MESSAGE_ID } from '../../../constants/message';
import { OrderListMixins } from '../../../behaviors/page';
import { getOrderList, payOrder, cancelOrder, cancelAfterSaleOrder,
    confirmExpressOrder, confirmPickupOrder, getAfterSaleList } from '../../api/order';
import { PACKAGE_ORDER_PAGE } from '../../../constants/route';
const { navTo, callPhone, showLoading, hideLoading, subscribeMessage } = require('../../../common/env');
import { isValidTime } from '../../../common/utils';
import { invokePlatformPay } from '../../../common/pay';
import { TipAlert, TipDialog } from '../../../common/tip';

Page({
    mixins: [OrderListMixins],
    data: {
        tabsData: ORDERLIST_TABS,
        orderTypesEnum: ORDER_TYPE_ENUM,
        orderList: [],
        afterSaleList: [],
    },
    onLoad: async function () {
        await this.getOrderListData();
    },
    // 获取订单列表
    getOrderListData: async function (isRefresh = false) {
        showLoading('加载中...');
        const { activeIndex, orderList, afterSaleList, pageSize, pageNo, pageTime } = this.data;
        let param = { pageSize, pageNo, pageTime };
        if (activeIndex === ORDER_TYPE_ENUM.afterSale) {
            // 售后
            const afterList = await getAfterSaleList(param);
            console.log('OrderList => 获取售后订单数据为：', afterList, isRefresh);
            this.setData({
                afterSaleList: isRefresh ? afterList : [...afterSaleList, ...afterList],
            });
        } else {
            const isAll = activeIndex === ORDER_TYPE_ENUM.all;
            if (isAll) {
                param.isAll = true;
            } else {
                param.orderStatus = ORDERLIST_TABS.filter(item => item.name === activeIndex)[0].value;
            }
            // 正常单
            const list = await getOrderList(param);
            console.log('OrderList => 获取订单数据为：', list, isRefresh);
            this.setData({
                orderList: isRefresh ? list : [...orderList, ...list],
            });
        }
        hideLoading();
    },
    // 订单详情
    invokeDetailAction: function (event) {
        const { serialNumber } = event.detail;
        navTo(PACKAGE_ORDER_PAGE.orderDetail, {
            orderNumber: serialNumber,
        });
    },
    // 售后单详情
    invokeAfterSaleDetailAction: function (event) {
        const { serialNumber } = event.detail;
        navTo(PACKAGE_ORDER_PAGE.orderAfterSaleDetail, {
            orderNumber: serialNumber,
        });
    },
    // 订单支付
    invokePayAction: async function (event) {
        const { serialNumber, amount, paymentDeadlineAt } = event.detail;
        const that = this;
        if (!isValidTime(paymentDeadlineAt)) {
            TipAlert({
                title: '支付超时',
                message: '订单支付已超时，订单已关闭。',
                ok: async () => {
                    await that.refreshListData();
                },
            })
            return;
        }
        const res = await payOrder(serialNumber, { amount });
        console.log('OrderList => 订单支付结果：', serialNumber, res);
        if (res) {
            await invokePlatformPay(res.transactionInfo);
            await this.refreshListData();
            await subscribeMessage([MESSAGE_ID.order_status, MESSAGE_ID.self_pickup]);
        }
    },
    // 订单取消
    invokeCancel: async function (event) {
        const { serialNumber } = event.detail;
        const res = await cancelOrder(serialNumber);
        console.log('OrderList => 订单取消结果：', serialNumber, res);
        if (res) {
            await this.refreshListData();
        }
    },
    // 售后单取消
    invokeCancelAfter: async function (event) {
        const { serialNumber } = event.detail;
        const res = await cancelAfterSaleOrder(serialNumber);
        console.log('OrderList => 售后单取消结果：', serialNumber, res);
        if (res) {
            await this.refreshListData();
        }
    },
    // 确认收货
    invokeExpressConfirm: async function (event) {
        const { serialNumber } = event.detail;
        const _ = this;
        TipDialog({
            title: '确认收货',
            message: '请确认您已经收到了货物',
            confirmButtonText: '确定收货',
            ok: async () => {
                const res = await confirmExpressOrder(serialNumber);
                console.log('OrderList => 订单确认收货结果：', serialNumber, res);
                if (res) {
                    await _.refreshListData();
                }
            },
        });
    },
    // 确认提货
    invokePickupConfirm: async function (event) {
        const { serialNumber } = event.detail;
        const _ = this;
        TipDialog({
            title: '确认提货',
            message: '请确认您已经提取了货物',
            confirmButtonText: '确定提货',
            ok: async () => {
                const res = await confirmPickupOrder(serialNumber);
                console.log('OrderList => 订单确认提货结果：', serialNumber, res);
                if (res) {
                    await _.refreshListData();
                }
            },
        });
    },
    // 联系商家
    invokeContact: function (event) {
        const { activityTel } = event.detail;
        callPhone(activityTel);
    },
})